package com.sunshine.serialport.view;


import com.sunshine.serialport.service.BaseService;
import com.sunshine.serialport.tools.query.QueryDTO;
import com.sunshine.serialport.tools.ServletUtil;
import com.sunshine.serialport.tools.query.SpecificationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:xiayingjie
 * @createTime:2020-06-02
 */

public class BaseController {

    /**
     * 分页查询列表
     * @param request
     * @param queryDTO
     * @param service
     * @param clz
     * @return
     */
    public Page search(HttpServletRequest request, QueryDTO queryDTO, BaseService service, Class clz){
              Map<String, String> searchMap = ServletUtil.getParametersStartingWith(request, "search");

        queryDTO.setPage(queryDTO.getPage() - 1);
        //查询结果
        Specification specification= SpecificationUtil.bySearchFilter(searchMap, clz);
        PageRequest pageRequest=SpecificationUtil.getPageRequest(queryDTO);
        Page page = service.findAll(specification,pageRequest);

        return page;
    }

    /**
     * 获取分页map
     * @param p
     * @param queryDTO
     * @return
     */
    public Map getPageMap(Page p, QueryDTO queryDTO){
        int page=queryDTO.getPage() < 1 ? 1 : queryDTO.getPage();
        int size=queryDTO.getSize();
        long allSize=p.getTotalElements();
        int allPage=p.getTotalPages();
        Map extraMap=new HashMap();
        extraMap.put("page", page);
        extraMap.put("totalPage", allPage);
        extraMap.put("size", size);
        extraMap.put("totalSize", allSize);
        return extraMap;
    }

    /**
     * 获取分页map
     * @param p
     * @param pageable
     * @return
     */
    public Map getPageMap(Page p, Pageable pageable){
        int page=pageable.getPageNumber() < 1 ? 1 : pageable.getPageNumber()+1;
        int size=pageable.getPageSize();
        long allSize=p.getTotalElements();
        int allPage=p.getTotalPages();
        Map extraMap=new HashMap();
        extraMap.put("page", page);
        extraMap.put("totalPage", allPage);
        extraMap.put("size", size);
        extraMap.put("totalSize", allSize);
        return extraMap;
    }



}
